﻿using Message;
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// 登录面板
/// </summary>
public class LoginView : ViewBase
{
    private InputField uname;
    private InputField pwd;

    private Button loginBtn;
    private Button backBtn;

    public override void Init(params object[] args)
    {
        base.Init(args);
        layer = PanelLayer.Panel;
    }

    public override void OnShowing()
    {
        base.OnShowing();
        Transform skinTrans = panelObj.transform;
        loginBtn = skinTrans.Find("loginBtn").GetComponent<Button>();
        backBtn = skinTrans.Find("backBtn").GetComponent<Button>();
        uname = skinTrans.Find("uname").GetComponent<InputField>();
        pwd = skinTrans.Find("pwd").GetComponent<InputField>();

        loginBtn.onClick.AddListener(OnLogin);
        backBtn.onClick.AddListener(OnBack);

        NetMgr.Instance.OnConnect += OnConnect;
    }

    private void OnLogin()
    {
        //连接服务器
        if (NetMgr.Instance.state != State.Connected)
        {
            NetMgr.Instance.Connect();
            return;
        }
        else
        {
            Login();
        }
    }

    void OnConnect(State status)
    {
        Log.Debug("status:" + status.ToString());
        if (status == State.Connected)
        {
            Login();
        }
        if (status == State.TimeOut)
        {
            UIMgr.Instance.Show<TipView>("连接服务器超时!");
        }
        if (status == State.Error)
        {
            UIMgr.Instance.Show<TipView>("连接服务器出错!");
        }
    }

    private void OnBack()
    {
        Close();
        UIMgr.Instance.Show<RegisterView>();
    }

    void Login()
    {
        //注册登录返回结果回调
        MsgMgr.Instance.AddListener(typeof(S2CLoginRet), OnLoginBack);

        //发送
        C2SLogin protocol = new C2SLogin();
        protocol.uname = uname.text;
        protocol.pwd = Util.GetStringHash(pwd.text);
        NetMgr.Instance.Send(protocol);
    }

    private void OnLoginBack(object obj)
    {
        Log.Debug("OnLoginBack");
        //移除登录返回结果回调
        MsgMgr.Instance.RemoveListener(typeof(S2CLoginRet), OnLoginBack);

        S2CLoginRet stcl = obj as S2CLoginRet;
        if (stcl.code == 0)
        {
            Log.Debug("uid:" + stcl.uid);
            GlobeData.uid = stcl.uid;
            GlobeData.uname = uname.text;
            UIMgr.Instance.Show<TipView>("登录成功!");
            //PanelMgr.Instance.OpenPanel<MainPanel>("MainPanel");
            UIMgr.Instance.Show<RoleView>();
            Close();
        }
        else
        {
            UIMgr.Instance.Show<TipView>("登录失败!");
        }
    }

    protected override void Close()
    {
        base.Close();
        NetMgr.Instance.OnConnect -= OnConnect;
    }
}